package com.example.mynote.activity;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.mynote.activity.MainActivity;
import com.example.mynote.R;
import com.example.mynote.base.BaseActivity;
import com.example.mynote.entity.User;

import org.litepal.LitePal;

import java.util.List;

public class LoginActivity extends BaseActivity {

    private android.widget.EditText username;
    private android.widget.EditText password;
    private android.widget.Button btnLogin;
    private android.widget.Button btnRegister;

    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {

        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btn_login);
        btnRegister = (Button) findViewById(R.id.btn_register);
    }

    @Override
    protected void initData() {

        btnLogin.setOnClickListener(v -> {
            String name = username.getText().toString();
            String pass = password.getText().toString();
            if (!name.equals("") && !pass.equals("")) {
                if (checkUser(name, pass)) {
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    getSharedPreferences("user", MODE_PRIVATE).edit().putString("name", name).apply();
                    intentTo(MainActivity.class);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(LoginActivity.this, "请检查用户名密码", Toast.LENGTH_SHORT).show();
            }
        });

        btnRegister.setOnClickListener(v -> {
            intentTo(RegisterActivity.class);
        });
    }

    private boolean checkUser(String name, String pass) {
        List<User> all = LitePal.findAll(User.class);
        for (int i = 0; i < all.size(); i++) {
            if (all.get(i).getUserName().equals(name) && all.get(i).getUserPass().equals(pass)) {
                return true;
            }
        }
        return false;
    }
}